"""
校园新生指引程序 - 现代化界面
简洁清新的校园风格设计，蓝绿色主题
"""

import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import sys
import os

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from models import CampusMap, Point, Road
from path_finder import PathFinder
from map_visualizer import MapVisualizer


class ModernCampusNavigator:
    """现代化校园新生指引程序主界面"""
    
    def __init__(self):
        # 初始化数据
        self.campus_map = CampusMap()
        self.path_finder = PathFinder(self.campus_map)
        self.map_visualizer = MapVisualizer(self.campus_map)
        self.map_editor = None
        self.edit_mode = False  # 编辑模式标志
        
        # 颜色主题
        self.colors = {
            'primary': '#2E8B57',        # 蓝绿色主色调
            'primary_hover': '#26734D',  # 悬停深色
            'background': '#FFFFFF',     # 白色背景
            'card_bg': '#FFFFFF',        # 卡片背景
            'border': '#E0E0E0',        # 浅灰边框
            'text_primary': '#333333',   # 主要文字
            'text_secondary': '#666666', # 次要文字
            'text_light': '#999999',     # 浅色文字
            'success': '#28A745',        # 成功色
            'warning': '#FFC107',        # 警告色
            'error': '#DC3545',          # 错误色
            'shadow': '#E8E8E8'          # 阴影（浅灰色）
        }
        
        # 字体设置
        self.fonts = {
            'title': ('Microsoft YaHei', 18, 'bold'),
            'subtitle': ('Microsoft YaHei', 14, 'bold'),
            'body': ('Microsoft YaHei', 12),
            'small': ('Microsoft YaHei', 10)
        }
        
        # 创建主窗口
        self.root = tk.Tk()
        self.root.title("校园新生指引助手")
        self.root.geometry("1200x800")
        self.root.minsize(800, 600)
        self.root.configure(bg=self.colors['background'])
        
        # 创建界面
        self.create_navbar()
        self.create_main_layout()
        
        # 加载示例数据
        self.load_sample_data()
        
        # 初始化地图显示
        self.init_map_display()
    
    def create_navbar(self):
        """创建顶部导航栏"""
        self.navbar = tk.Frame(self.root, height=60, bg=self.colors['primary'])
        self.navbar.pack(fill=tk.X, padx=0, pady=0)
        self.navbar.pack_propagate(False)  # 固定高度
        
        # 程序标题
        title_label = tk.Label(
            self.navbar,
            text="校园新生指引助手",
            font=self.fonts['title'],
            fg='white',
            bg=self.colors['primary']
        )
        title_label.pack(side=tk.LEFT, padx=20, pady=15)
        
        # 帮助按钮
        help_button = tk.Button(
            self.navbar,
            text="?",
            font=('Microsoft YaHei', 14, 'bold'),
            fg='white',
            bg=self.colors['primary'],
            relief='flat',
            cursor='hand2',
            command=self.show_help
        )
        help_button.pack(side=tk.RIGHT, padx=20, pady=15)
        
        # 添加阴影效果
        shadow_frame = tk.Frame(self.root, height=2, bg=self.colors['shadow'])
        shadow_frame.pack(fill=tk.X)
    
    def create_main_layout(self):
        """创建主布局"""
        # 主容器
        main_container = tk.Frame(self.root, bg=self.colors['background'])
        main_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 左侧地图区域 (60%)
        self.map_frame = tk.Frame(main_container, bg=self.colors['background'])
        self.map_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
        
        # 右侧功能区域 (300px固定宽度)
        self.sidebar = tk.Frame(main_container, width=300, bg=self.colors['background'])
        self.sidebar.pack(side=tk.RIGHT, fill=tk.Y, padx=(10, 0))
        self.sidebar.pack_propagate(False)  # 固定宽度
        
        # 创建地图区域
        self.create_map_area()
        
        # 创建功能侧边栏
        self.create_sidebar()
        
        # 创建底部状态栏
        self.create_statusbar()
    
    def create_map_area(self):
        """创建地图显示区域"""
        # 地图容器
        map_container = tk.Frame(
            self.map_frame,
            bg=self.colors['card_bg'],
            relief='solid',
            bd=1,
            highlightbackground=self.colors['border']
        )
        map_container.pack(fill=tk.BOTH, expand=True)
        
        # 地图控制按钮
        control_frame = tk.Frame(map_container, bg=self.colors['card_bg'])
        control_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 控制按钮
        controls = [
            ("放大", self.zoom_in),
            ("缩小", self.zoom_out),
            ("重置", self.reset_view)
        ]
        
        for text, command in controls:
            btn = tk.Button(
                control_frame,
                text=text,
                font=self.fonts['small'],
                bg=self.colors['primary'],
                fg='white',
                relief='flat',
                cursor='hand2',
                command=command
            )
            btn.pack(side=tk.LEFT, padx=5)
        
        # 地图显示区域
        self.map_display_frame = tk.Frame(
            map_container,
            bg='white',
            relief='sunken',
            bd=1
        )
        self.map_display_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        
        # 初始提示文本
        self.map_label = tk.Label(
            self.map_display_frame,
            text="正在初始化地图...",
            font=self.fonts['body'],
            bg='white',
            fg=self.colors['text_secondary']
        )
        self.map_label.pack(expand=True)
    
    def create_sidebar(self):
        """创建右侧功能侧边栏"""
        # 点位管理卡片
        self.create_point_card()
        
        # 路径规划卡片
        self.create_route_card()
        
        # 信息展示卡片
        self.create_info_card()
    
    def create_point_card(self):
        """创建点位管理卡片"""
        card = self.create_card(self.sidebar, "点位管理")
        
        # 按钮容器
        button_frame = tk.Frame(card, bg=self.colors['card_bg'])
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        buttons = [
            ("添加点位", self.add_point),
            ("删除点位", self.delete_point),
            ("修改位置", self.edit_point),
            ("添加标记", self.add_marker),
            ("清除标记", self.clear_markers)
        ]
        
        for text, command in buttons:
            btn = tk.Button(
                button_frame,
                text=text,
                font=self.fonts['body'],
                bg=self.colors['primary'],
                fg='white',
                relief='flat',
                cursor='hand2',
                command=command
            )
            btn.pack(fill=tk.X, pady=2)
    
    def create_route_card(self):
        """创建路径规划卡片"""
        card = self.create_card(self.sidebar, "路径规划")
        
        # 起点选择
        tk.Label(
            card,
            text="当前点位:",
            font=self.fonts['small'],
            bg=self.colors['card_bg'],
            fg=self.colors['text_primary']
        ).pack(anchor=tk.W, padx=10, pady=(10, 5))
        
        self.start_var = tk.StringVar()
        self.start_combo = ttk.Combobox(
            card,
            textvariable=self.start_var,
            font=self.fonts['body'],
            state='readonly'
        )
        self.start_combo.pack(fill=tk.X, padx=10, pady=(0, 10))
        
        # 目标功能选择
        tk.Label(
            card,
            text="目标功能:",
            font=self.fonts['small'],
            bg=self.colors['card_bg'],
            fg=self.colors['text_primary']
        ).pack(anchor=tk.W, padx=10, pady=(5, 5))
        
        self.target_var = tk.StringVar()
        self.target_combo = ttk.Combobox(
            card,
            textvariable=self.target_var,
            font=self.fonts['body'],
            state='readonly'
        )
        self.target_combo.pack(fill=tk.X, padx=10, pady=(0, 10))
        
        # 查询按钮
        find_btn = tk.Button(
            card,
            text="查询路线",
            font=self.fonts['body'],
            bg=self.colors['primary'],
            fg='white',
            relief='flat',
            cursor='hand2',
            command=self.find_route
        )
        find_btn.pack(fill=tk.X, padx=10, pady=10)
    
    def create_info_card(self):
        """创建信息展示卡片"""
        card = self.create_card(self.sidebar, "信息展示")
        
        # 路线结果显示
        tk.Label(
            card,
            text="路线结果:",
            font=self.fonts['small'],
            bg=self.colors['card_bg'],
            fg=self.colors['text_primary']
        ).pack(anchor=tk.W, padx=10, pady=(10, 5))
        
        route_frame = tk.Frame(card, bg=self.colors['card_bg'])
        route_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        
        self.route_text = tk.Text(
            route_frame,
            height=8,
            font=self.fonts['small'],
            wrap=tk.WORD,
            relief='solid',
            bd=1
        )
        self.route_text.pack(fill=tk.BOTH, expand=True)
        
        # 功能信息显示
        tk.Label(
            card,
            text="功能信息:",
            font=self.fonts['small'],
            bg=self.colors['card_bg'],
            fg=self.colors['text_primary']
        ).pack(anchor=tk.W, padx=10, pady=(10, 5))
        
        info_frame = tk.Frame(card, bg=self.colors['card_bg'])
        info_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        
        self.info_text = tk.Text(
            info_frame,
            height=6,
            font=self.fonts['small'],
            wrap=tk.WORD,
            relief='solid',
            bd=1
        )
        self.info_text.pack(fill=tk.BOTH, expand=True)
    
    def create_statusbar(self):
        """创建底部状态栏"""
        self.statusbar = tk.Frame(
            self.root,
            height=30,
            bg=self.colors['background'],
            relief='solid',
            bd=1,
            highlightbackground=self.colors['border']
        )
        self.statusbar.pack(fill=tk.X, side=tk.BOTTOM)
        self.statusbar.pack_propagate(False)
        
        # 缩放比例显示
        self.scale_label = tk.Label(
            self.statusbar,
            text="缩放: 100%",
            font=self.fonts['small'],
            bg=self.colors['background'],
            fg=self.colors['text_light']
        )
        self.scale_label.pack(side=tk.LEFT, padx=10, pady=5)
        
        # 操作提示
        self.hint_label = tk.Label(
            self.statusbar,
            text="点击点位可查看详情",
            font=self.fonts['small'],
            bg=self.colors['background'],
            fg=self.colors['text_light']
        )
        self.hint_label.pack(side=tk.RIGHT, padx=10, pady=5)
    
    def create_card(self, parent, title):
        """创建卡片式容器"""
        card = tk.Frame(
            parent,
            bg=self.colors['card_bg'],
            relief='solid',
            bd=1,
            highlightbackground=self.colors['border']
        )
        card.pack(fill=tk.X, pady=(0, 15))
        
        # 卡片标题
        title_label = tk.Label(
            card,
            text=title,
            font=self.fonts['subtitle'],
            bg=self.colors['card_bg'],
            fg=self.colors['text_primary']
        )
        title_label.pack(anchor=tk.W, padx=15, pady=10)
        
        return card
    
    def load_sample_data(self):
        """加载示例数据"""
        try:
            # 创建示例点位
            points_data = [
                {"id": "p1", "name": "大门", "x": 10, "y": 50, "functions": ["入口"], "description": "校园主入口"},
                {"id": "p2", "name": "南苑食堂", "x": 40, "y": 60, "functions": ["领取军训服", "领取床铺用品", "就餐"], "description": "南苑学生食堂"},
                {"id": "p3", "name": "崇礼楼", "x": 70, "y": 40, "functions": ["材料工程学院", "教学楼"], "description": "材料工程学院所在地"},
                {"id": "p4", "name": "计通楼", "x": 30, "y": 30, "functions": ["计算机学院", "教学楼"], "description": "计算机与通信工程学院"},
                {"id": "p5", "name": "图书馆", "x": 60, "y": 20, "functions": ["借阅图书", "自习"], "description": "校园图书馆"},
                {"id": "p6", "name": "体育馆", "x": 80, "y": 70, "functions": ["体育课", "健身"], "description": "校园体育馆"}
            ]
            
            for point_data in points_data:
                point = Point.from_dict(point_data)
                self.campus_map.add_point(point)
            
            # 创建示例道路
            roads_data = [
                {"id": "r1", "point1_id": "p1", "point2_id": "p2", "distance": 150, "description": "主干道"},
                {"id": "r2", "point1_id": "p1", "point2_id": "p4", "distance": 120, "description": "林荫道"},
                {"id": "r3", "point1_id": "p2", "point2_id": "p3", "distance": 200, "description": "环校路"},
                {"id": "r4", "point1_id": "p2", "point2_id": "p6", "distance": 180, "description": "体育路"},
                {"id": "r5", "point1_id": "p3", "point2_id": "p5", "distance": 160, "description": "学术路"},
                {"id": "r6", "point1_id": "p4", "point2_id": "p5", "distance": 140, "description": "图书馆路"},
                {"id": "r7", "point1_id": "p5", "point2_id": "p6", "distance": 220, "description": "环湖路"}
            ]
            
            for road_data in roads_data:
                road = Road.from_dict(road_data)
                self.campus_map.add_road(road)
            
            # 更新界面
            self.update_ui()
            
        except Exception as e:
            messagebox.showerror("错误", f"加载示例数据失败: {str(e)}")
    
    def update_ui(self):
        """更新界面数据"""
        # 更新下拉框
        point_names = [point.name for point in self.campus_map.points.values()]
        functions = self.campus_map.get_all_functions()
        
        self.start_combo['values'] = point_names
        self.target_combo['values'] = functions
    
    def init_map_display(self):
        """初始化地图显示"""
        try:
            # 移除初始提示文本
            self.map_label.destroy()
            
            # 创建matplotlib画布并嵌入到Tkinter界面
            self.map_canvas = self.map_visualizer.create_tk_canvas(self.map_display_frame)
            self.map_canvas.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
            
            # 初始化地图编辑器
            from map_visualizer import MapEditor
            self.map_editor = MapEditor(self.campus_map, self.map_visualizer)
            self.map_editor.connect_events(self.map_visualizer.canvas)
            
            # 绘制地图
            self.map_visualizer.draw_map()
            
        except Exception as e:
            messagebox.showerror("地图初始化错误", f"无法初始化地图显示: {str(e)}")
    
    def show_help(self):
        """显示帮助信息"""
        help_text = """
校园新生指引助手使用指南

1. 地图操作
   • 鼠标拖拽：平移地图
   • 滚轮滚动：缩放地图
   • 点击点位：查看点位详情

2. 路径规划
   • 选择起点点位
   • 选择目标功能
   • 点击"查询路线"获取最优路径

3. 点位管理
   • 添加点位：创建新的校园点位
   • 删除点位：移除不需要的点位
   • 修改位置：调整点位坐标

如有问题，请联系校园信息化中心。
        """
        messagebox.showinfo("使用帮助", help_text)
    
    def add_point(self):
        """添加点位"""
        dialog = ModernPointDialog(self.root, self.colors, self.fonts)
        if dialog.result:
            try:
                point_data = dialog.result
                point = Point(
                    id=f"point_{len(self.campus_map.points) + 1}",
                    name=point_data['name'],
                    x=point_data['x'],
                    y=point_data['y'],
                    functions=point_data['functions'],
                    description=point_data['description']
                )
                self.campus_map.add_point(point)
                self.update_ui()
                self.map_visualizer.draw_map()  # 更新地图
                messagebox.showinfo("成功", f"已添加点位: {point.name}")
            except Exception as e:
                messagebox.showerror("错误", f"添加点位失败: {str(e)}")
    
    def delete_point(self):
        """删除点位"""
        if not self.campus_map.points:
            messagebox.showinfo("提示", "没有可删除的点位")
            return
        
        point_names = [point.name for point in self.campus_map.points.values()]
        point_name = simpledialog.askstring("删除点位", "选择要删除的点位:", 
                                           initialvalue=point_names[0] if point_names else "")
        
        if point_name:
            point = self.campus_map.get_point_by_name(point_name)
            if point:
                self.campus_map.remove_point(point.id)
                self.update_ui()
                self.map_visualizer.draw_map()  # 更新地图
                messagebox.showinfo("成功", f"已删除点位: {point_name}")
    
    def edit_point(self):
        """修改点位位置"""
        if not self.edit_mode:
            # 进入编辑模式
            self.edit_mode = True
            self.hint_label.config(text="拖拽模式：点击并拖拽点位可调整位置")
            messagebox.showinfo("编辑模式", "已进入点位编辑模式\n\n操作说明：\n• 点击并拖拽点位可调整位置\n• 再次点击'修改位置'按钮退出编辑模式")
        else:
            # 退出编辑模式
            self.edit_mode = False
            self.hint_label.config(text="点击点位可查看详情")
            messagebox.showinfo("编辑模式", "已退出点位编辑模式")
    
    def find_route(self):
        """查询路线"""
        start_point = self.start_var.get()
        target_function = self.target_var.get()
        
        if not start_point:
            messagebox.showwarning("输入错误", "请选择起点点位")
            return
        
        if not target_function:
            messagebox.showwarning("输入错误", "请选择目标功能")
            return
        
        try:
            # 规划路线
            route_description = self.path_finder.find_route_by_function(start_point, target_function)
            
            # 显示路线结果
            self.route_text.delete(1.0, tk.END)
            self.route_text.insert(1.0, route_description)
            
            # 显示功能信息
            points = self.campus_map.get_points_by_function(target_function)
            info_text = f"提供 '{target_function}' 功能的点位:\n\n"
            for point in points:
                info_text += f"• {point.name}\n"
                if point.description:
                    info_text += f"  描述: {point.description}\n"
                info_text += "\n"
            
            self.info_text.delete(1.0, tk.END)
            self.info_text.insert(1.0, info_text)
            
            messagebox.showinfo("成功", "路线规划完成")
            
        except Exception as e:
            messagebox.showerror("错误", f"路线规划失败: {str(e)}")
    
    def zoom_in(self):
        """放大地图"""
        try:
            # 这里可以添加实际的放大逻辑
            messagebox.showinfo("功能提示", "地图放大功能")
        except Exception as e:
            messagebox.showerror("错误", f"放大操作失败: {str(e)}")
    
    def zoom_out(self):
        """缩小地图"""
        try:
            # 这里可以添加实际的缩小逻辑
            messagebox.showinfo("功能提示", "地图缩小功能")
        except Exception as e:
            messagebox.showerror("错误", f"缩小操作失败: {str(e)}")
    
    def add_marker(self):
        """添加标记方块"""
        try:
            # 获取标记参数
            x = simpledialog.askfloat("添加标记", "请输入X坐标:", initialvalue=50)
            if x is None:
                return
            
            y = simpledialog.askfloat("添加标记", "请输入Y坐标:", initialvalue=50)
            if y is None:
                return
            
            width = simpledialog.askfloat("添加标记", "请输入方块宽度:", initialvalue=10)
            if width is None:
                return
            
            height = simpledialog.askfloat("添加标记", "请输入方块高度:", initialvalue=10)
            if height is None:
                return
            
            label = simpledialog.askstring("添加标记", "请输入标记标签(可选):")
            
            # 添加标记
            self.map_editor.add_marker(x, y, width, height, label=label)
            messagebox.showinfo("成功", f"已添加标记到位置({x}, {y})")
            
        except Exception as e:
            messagebox.showerror("错误", f"添加标记失败: {str(e)}")
    
    def clear_markers(self):
        """清除所有标记"""
        try:
            self.map_editor.clear_markers()
            messagebox.showinfo("成功", "已清除所有标记")
        except Exception as e:
            messagebox.showerror("错误", f"清除标记失败: {str(e)}")
    
    def reset_view(self):
        """重置视图"""
        try:
            # 重新绘制地图
            self.map_visualizer.draw_map()
            messagebox.showinfo("成功", "地图视图已重置")
        except Exception as e:
            messagebox.showerror("错误", f"重置视图失败: {str(e)}")
    
    def run(self):
        """运行程序"""
        self.root.mainloop()


class ModernPointDialog:
    """现代化点位对话框"""
    
    def __init__(self, parent, colors, fonts):
        self.parent = parent
        self.colors = colors
        self.fonts = fonts
        self.result = None
        
        self.dialog = tk.Toplevel(parent)
        self.dialog.title("添加点位")
        self.dialog.geometry("400x350")
        self.dialog.configure(bg=colors['background'])
        self.dialog.transient(parent)
        self.dialog.grab_set()
        
        self.setup_ui()
    
    def setup_ui(self):
        """设置对话框界面"""
        # 主框架
        main_frame = tk.Frame(self.dialog, bg=self.colors['background'], padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = tk.Label(
            main_frame,
            text="添加点位",
            font=self.fonts['subtitle'],
            bg=self.colors['background'],
            fg=self.colors['text_primary']
        )
        title_label.pack(anchor=tk.W, pady=(0, 15))
        
        # 点位名称
        tk.Label(
            main_frame,
            text="点位名称:",
            font=self.fonts['small'],
            bg=self.colors['background'],
            fg=self.colors['text_primary']
        ).pack(anchor=tk.W, pady=(5, 2))
        
        self.name_var = tk.StringVar()
        self.name_entry = tk.Entry(
            main_frame,
            textvariable=self.name_var,
            font=self.fonts['body'],
            relief='solid',
            bd=1
        )
        self.name_entry.pack(fill=tk.X, pady=(0, 10))
        
        # 坐标
        coord_frame = tk.Frame(main_frame, bg=self.colors['background'])
        coord_frame.pack(fill=tk.X, pady=(5, 10))
        
        # X坐标
        tk.Label(
            coord_frame,
            text="X坐标:",
            font=self.fonts['small'],
            bg=self.colors['background'],
            fg=self.colors['text_primary']
        ).pack(side=tk.LEFT, padx=(0, 10))
        
        self.x_var = tk.StringVar(value="50")
        self.x_entry = tk.Entry(
            coord_frame,
            textvariable=self.x_var,
            font=self.fonts['body'],
            width=10,
            relief='solid',
            bd=1
        )
        self.x_entry.pack(side=tk.LEFT, padx=(0, 20))
        
        # Y坐标
        tk.Label(
            coord_frame,
            text="Y坐标:",
            font=self.fonts['small'],
            bg=self.colors['background'],
            fg=self.colors['text_primary']
        ).pack(side=tk.LEFT, padx=(0, 10))
        
        self.y_var = tk.StringVar(value="50")
        self.y_entry = tk.Entry(
            coord_frame,
            textvariable=self.y_var,
            font=self.fonts['body'],
            width=10,
            relief='solid',
            bd=1
        )
        self.y_entry.pack(side=tk.LEFT)
        
        # 功能列表
        tk.Label(
            main_frame,
            text="功能列表:",
            font=self.fonts['small'],
            bg=self.colors['background'],
            fg=self.colors['text_primary']
        ).pack(anchor=tk.W, pady=(5, 2))
        
        tk.Label(
            main_frame,
            text="用逗号分隔，如：就餐,领取物品",
            font=('Microsoft YaHei', 8),
            bg=self.colors['background'],
            fg=self.colors['text_light']
        ).pack(anchor=tk.W, pady=(0, 2))
        
        self.functions_var = tk.StringVar()
        self.functions_entry = tk.Entry(
            main_frame,
            textvariable=self.functions_var,
            font=self.fonts['body'],
            relief='solid',
            bd=1
        )
        self.functions_entry.pack(fill=tk.X, pady=(0, 10))
        
        # 描述
        tk.Label(
            main_frame,
            text="点位描述:",
            font=self.fonts['small'],
            bg=self.colors['background'],
            fg=self.colors['text_primary']
        ).pack(anchor=tk.W, pady=(5, 2))
        
        self.description_text = tk.Text(
            main_frame,
            height=4,
            font=self.fonts['body'],
            wrap=tk.WORD,
            relief='solid',
            bd=1
        )
        self.description_text.pack(fill=tk.X, pady=(0, 20))
        
        # 按钮
        button_frame = tk.Frame(main_frame, bg=self.colors['background'])
        button_frame.pack(fill=tk.X)
        
        ok_btn = tk.Button(
            button_frame,
            text="确定",
            font=self.fonts['body'],
            bg=self.colors['primary'],
            fg='white',
            relief='flat',
            cursor='hand2',
            command=self.on_ok
        )
        ok_btn.pack(side=tk.RIGHT, padx=(10, 0))
        
        cancel_btn = tk.Button(
            button_frame,
            text="取消",
            font=self.fonts['body'],
            bg=self.colors['border'],
            fg=self.colors['text_primary'],
            relief='flat',
            cursor='hand2',
            command=self.on_cancel
        )
        cancel_btn.pack(side=tk.RIGHT)
        
        # 焦点设置
        self.name_entry.focus()
    
    def on_ok(self):
        """确定按钮处理"""
        try:
            name = self.name_var.get().strip()
            if not name:
                messagebox.showwarning("输入错误", "点位名称不能为空")
                return
            
            x = float(self.x_var.get())
            y = float(self.y_var.get())
            
            functions_text = self.functions_var.get().strip()
            functions = [f.strip() for f in functions_text.split(',') if f.strip()]
            
            description = self.description_text.get(1.0, tk.END).strip()
            
            self.result = {
                'name': name,
                'x': x,
                'y': y,
                'functions': functions,
                'description': description
            }
            
            self.dialog.destroy()
            
        except ValueError:
            messagebox.showerror("输入错误", "坐标必须是有效的数字")
    
    def on_cancel(self):
        """取消按钮处理"""
        self.result = None
        self.dialog.destroy()


if __name__ == "__main__":
    app = ModernCampusNavigator()
    app.run()
